<template>
  <div>
    <!-- 面包屑导航开始想要修改组件原有样式时尽量把后来修改的样式写在全局样式里面 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 -->
    <el-card>
      <!-- 搜索与添加框 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="paramsData.query"
            clearable
            @clear="getUsersData()"
          >
            <el-button slot="append" icon="el-icon-search" @click="getUsersData()"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="isVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 搜索框结束 -->

      <!-- 用户列表区域开始 -->
      <!-- 组件提供的方法绑定要循环的数据 -->
      <el-table :data="usersData" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" prop="mg_state">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="statusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <!-- 操作列的渲染必须使用作用域插槽因为对数据的删除和修改必须根据id所以在渲染的时候利用插槽携带id数据 -->
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditData(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeData(scope.row.id)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRoles(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="paramsData.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="paramsData.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalData"
      ></el-pagination>
    </el-card>

    <!-- 添加用户框  @close="addClose 当点击添加按钮时触发addClose事件-->
    <el-dialog title="添加用户" :visible.sync="isVisible" width="50%" @close="addClose">
      <!-- 内容区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="isVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCommit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog title="修改用户" :visible.sync="EditisVisible" width="50%" @close="editClose">
      <!-- 内容区域 -->
      <!-- 添加时验证过了，点击修改框显示出来的内容不需要再次验证 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click=" EditisVisible = false">取 消</el-button>
        <el-button type="primary" @click="editData">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配用户 -->
    <el-dialog title="权限分配" :visible.sync="IssetRoles" width="50%">
      <div>
        <p>用户名:{{userInfo.username}}</p>
        <p>角色名:{{userInfo.role_name}}</p>
        <p>
          分配新角色:
          <el-select v-model="selectRolesId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="IssetRoles = false">取 消</el-button>
        <el-button type="primary" @click="commitRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 校验邮箱的规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确的邮箱'))
    }
    // 校验手机号的规则
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确的手机号'))
    }

    return {
      paramsData: {
        query: '',
        //当前显示页数
        pagenum: 1,
        //每页显示条数
        pagesize: 2
      },
      usersData: [],
      //总共有多少条数据
      totalData: 0,
      //添加用户框的显示
      isVisible: false,
      //添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      //需要被分配角色的用户信息
      userInfo: {},
      IssetRoles: false,
      //角色列表数据
      rolesList:[],
      //选中的下拉列表角色ID
     selectRolesId:'',
      // 添加表单验证规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        //密码验证
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 25,
            message: '长度在 6 到 15 个字符',
            trigger: 'blur'
          },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 11,
            message: '长度在 6 到 15 个字符',
            trigger: 'blur'
          },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      //修改用户框的显示
      EditisVisible: false,
      editForm: {},
      editFormRules: {
        email: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 25,
            message: '长度在 6 到 15 个字符',
            trigger: 'blur'
          },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 11,
            message: '长度在 6 到 15 个字符',
            trigger: 'blur'
          },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  //页面刚加载就发起请求
  created() {
    this.getUsersData()
  },
  methods: {
    handleSizeChange(newSize) {
      // console.log(newSize)当每页显示条数发生变化时需要重新赋值
      this.paramsData.pagesize = newSize
      //重新改变数据后应该向服务器在此发送请求进行渲染
      this.getUsersData()
    },
    //监听当前页码值的变化
    handleCurrentChange(newPage) {
      //console.log(newPage)
      this.paramsData.pagenum = newPage
      this.getUsersData()
    },
    async statusChange(newStatus) {
      //console.log(newStatus)当用户状态发生改变时立即向服务器发送修改请求
      const { data: res } = await this.$http.put(
        `users/${newStatus.id}/state/${newStatus.mg_state}`
      )
      //console.log(res)
      if (res.meta.status !== 200) {
        //更新状态失败时应该将页面的按钮状态还原
        newStatus.mg_state = !newStatus.mg_state
        return this.$message.error('更新状态失败')
      }
      this.$message.success('状态更新成功')
    },
    async getUsersData() {
      const { data: res } = await this.$http.get('users', {
        params: this.paramsData
      })
      //console.log(res)
      if (res.meta.status !== 200) return this.$message('获取数据失败')
      this.usersData = res.data.users
      this.totalData = res.total
    },
    //监听添加用户框关闭事件重置表单数据
    addClose() {
      this.$refs.addFormRef.resetFields()
    },
    //添加表单提交事件并发起请求
    addCommit() {
      //对表单数据进行验证
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        //向服务器发送请求提交表单数据
        const { data: res } = await this.$http.post('users', this.addForm)
        //console.log(res)
        //    // console.log(res.meta.status)请求状态码
        if (res.meta.status != 201) return this.$message.error('提交用户失败')

        this.$message.success('提交成功')
        // //提交成功后将添加用户框隐藏
        this.isVisible = false
        //  //重新发送get请求将数据渲染到页面
        this.getUsersData()
      })
    },
    //修改用户对话框的显示与隐藏
    async showEditData(id) {
      //console.log(id)根据id查询将数据渲染出来
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200)
        return this.$message.error('获取用户数据失败')
      this.editForm = res.data
      //让修改框显示出来
      this.EditisVisible = true
    },
    //点击重置修改表单操作
    editClose() {
      this.$refs.editFormRef.resetFields()
    },
    //修改用户信息并进行验证，提交
    editData() {
      this.$refs.editFormRef.validate(async valid => {
        //console.log(valid)
        if (!valid) return
        //成功后向服务器发送请求动态参数id在修改查询时已被保存在editForm中
        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          { email: this.editForm.email, mobile: this.editForm.mobile }
        )
        if (res.meta.status !== 200) return this.$message.error('更新数据失败')
        //  //重新发送get请求将数据渲染到页面
        this.getUsersData()
        //提示用户数据修改成功
        this.$message.success('数据修改成功')
      })
      this.EditisVisible = false
    },
    //删除数据操作
    async removeData(id) {
      //console.log(id)
      const confirmRes = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // console.log(confirmRes)点击确定返回的结果是confirm,点击取消 返回的结果是concel
      if (confirmRes !== 'confirm') {
        return this.$message.info('该操作已经取消')
      }
      //发送请求删除数据
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除数据失败')
      //提示客户删除数据成功
      this.$message.success('删除数据成功')
      //重新发送get请求将数据渲染到页面
      this.getUsersData()
    },
    //分配角色框
    async setRoles(userInfo) {
      this.userInfo = userInfo
     
      // 获取角色列表信息
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200)
        return this.$message.error('获取角色信息失败')
      this.rolesList = res.data
      this.$message.success('获取角色信息成功')
      this.IssetRoles = true
    },
    //点击按钮分配角色
   async commitRoles(){
      if(!this.selectRolesId) return this.$message.error('请选择角色信息')
      const {data:res}=await this.$http.put(`users/${this.userInfo.id}/role`,{rid:this.selectRolesId})
      console.log(res)
      this.IssetRoles = false
    }
  }
}
</script>

<style lang="less" scoped>
</style>